/****************************************************************
 *                                                              *
 * Copyright (c) 2001-2011 McObject LLC. All Rights Reserved.   *
 *                                                              *
 ****************************************************************/
#include <stdio.h>
#include <common.h>
#include <rsqldb.h>
#include <extreme_api.h>


const char *db_name             = "rsqldb";

MCO_RET connect_db(mco_db_h *db)
{
    return mco_db_connect( db_name, db );
}

MCO_RET disconnect_db(mco_db_h db)
{
    return mco_db_disconnect( db );
}

MCO_RET reset_connect(mco_db_h *db)
{
    MCO_RET rc;
    rc = disconnect_db(*db);

    if (rc == MCO_S_OK)
    {
        rc = connect_db(db_name, db);
    }

    return rc;
}

MCO_RET insert_db(mco_db_h db, aRecordData data)
{
    MCO_RET rc;
    MCO_RET find_rc;
    aRecord rec;
    aRecord find_rec;
    mco_trans_h t;
    uint4 key = data.id;

    rc = mco_trans_start(db, MCO_READ_WRITE, MCO_TRANS_FOREGROUND, &t);
    if ( MCO_S_OK == rc )
    {
        rc = aRecord_new(t, &rec);
        if ( MCO_S_OK == rc )
        {
            find_rc = aRecord_hid_find(t, key, &find_rec);
            if (find_rc == MCO_S_OK)
                aRecord_delete(&find_rec);
            aRecord_longitude_put(&rec, data.longitude);
            aRecord_latitude_put(&rec, data.latitude);
            aRecord_dat_put(&rec, (mco_date)data.dat);
            aRecord_tim_put(&rec, (mco_time)data.tim);
            rc = aRecord_id_put(&rec, key);
        }
        rc = mco_trans_commit(t);
    }
    return rc;
}


